package com.bc.trade.noitfy;


import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.Callable;

import com.bc.common.CommonEnum.NotifyStatus;
import com.bc.trade.model.Org;
import com.bc.trade.model.TradeOrder;
import com.fs.common.util.FSHttp;
import com.fs.common.util.FSJson;
import com.fs.common.util.FSLog;
import com.fs.common.util.FSMD5;

public class NotifyProcessThread implements Callable<List<NotifyThreadData>> {
	
	private static final int MAX_PUSH = 10;

	private Vector<NotifyThreadData> dataList = new Vector<>();

	public NotifyProcessThread(Vector<NotifyThreadData> dataList) {
		this.dataList = dataList;
	}

	@Override
	public List<NotifyThreadData> call() {
		NotifyReq notifyReq;
		NotifyThreadData data;
		List<NotifyThreadData> needRemoveList = new ArrayList<>();
		// 每个线程循环分配到的集合
		for (int i = 0; i < dataList.size(); i++) {
			data = dataList.get(i);
			if(data.getCurrentPushCount() >= MAX_PUSH){
				needRemoveList.add(data);
				continue;
			}
			
			// 开始推送 判断是交易订单还是代付订单
			notifyReq = data.getReq();
			String safeKey = Org.dao.selectSafeKey(notifyReq.getOrgCode());
			notifyReq.setSign(FSMD5.sortSign(notifyReq, safeKey));
			String sendResult = "";
			try {
				//5秒推送和接收
				sendResult = FSHttp.postJson(notifyReq.getNotifyUrl(), FSJson.toString(notifyReq),5000,5000);
			} catch (Exception e) {
				data.setCurrentPushCount(data.getCurrentPushCount() + 1);
				FSLog.api.error("订单号=" + notifyReq.getOrderNo() + "通知商户发生异常,当前次数="+data.getCurrentPushCount()+"异常信息->",e);
				continue;
			}

			if (("SUCCESS").equalsIgnoreCase(sendResult)) {
				TradeOrder.dao.updateNotifyStatus(notifyReq.getOrderNo(),NotifyStatus.Success.getValue());
				// 放入需要删除的集合中,返回到主线程进行删除
				needRemoveList.add(data);
				System.out.println("通知商户成功,订单号=" + notifyReq.getOrderNo());
			} else {
				data.setCurrentPushCount(data.getCurrentPushCount() + 1);
				System.out.println("通知商户失败,订单号=" + notifyReq.getOrderNo() + ",返回->" + sendResult + "->当前推送次数=" + data.getCurrentPushCount());
			}

		}
		return needRemoveList;
	}

}
